﻿@page "/Quartz_Manage/Quartz_Task/List"

@inherits BaseListWithEdit<Quartz_TaskDTO, EditForm>

<Space Size="@("small")">

    @if (Operator.HasPerm("Quartz_Task.Add"))
    {
        <SpaceItem>
            <Button Type="@ButtonType.Primary" Icon="plus" OnClick="()=>Edit()">新建</Button>
        </SpaceItem>
    }
    @if (Operator.HasPerm("Quartz_Task.Edit"))
    {
        <SpaceItem>
            <Button Type="@ButtonType.Primary" Icon="plus" OnClick="()=>Pause()" Disabled=@NoneSelectedItems>暂停</Button>
        </SpaceItem>
        <SpaceItem>
            <Button Type="@ButtonType.Primary" Icon="plus" OnClick="()=>Start()" Disabled=@NoneSelectedItems>开启</Button>
        </SpaceItem>   <SpaceItem>
            <Button Type="@ButtonType.Primary" Icon="plus" OnClick="()=> ToDo()" Disabled=@NoneSelectedItems>立即执行</Button>
        </SpaceItem>
    }
    @if (Operator.HasPerm("Quartz_Task.Delete"))
    {
        <SpaceItem>
            <Popconfirm Title="确认删除选中项吗?"
                    OnConfirm="()=>Delete()"
                    OnCancel="()=>{}"
                    OkText="确定"
                    CancelText="取消"
                    Disabled=@NoneSelectedItems>
                <Button Type="@ButtonType.Primary" Danger Icon="minus" Disabled=@NoneSelectedItems>删除</Button>
            </Popconfirm>
        </SpaceItem>
    }
    <SpaceItem>
        <Search Placeholder="关键字" EnterButton="true" @bind-Value="@KeyWord" OnSearch="()=>Refresh()" />
    </SpaceItem>
</Space>

<Table @ref="_table"
       TItem="Quartz_TaskDTO"
       DataSource="Data"
       EnableVirtualization
       Loading="Loading"
       @bind-PageSize="Pagination.PageRows"
       @bind-SelectedRows="SelectedItems"
       ScrollX="1800"
       ScrollBarWidth="12px"
       Size="TableSize.Small"
       RowClassName="@(x => x.RowIndex % 2 == 0 ?"gray-2":"")">
    <ChildContent>
        <Selection Key="@(context.Id)" />
        <AntDesign.Column Title="作业名称" DataIndex="TaskName" TData="string" />
        <AntDesign.Column Title="分组" DataIndex="GroupName" TData="string" />
        <AntDesign.Column Title="启用" DataIndex="IsEnabled" TData="bool" />
        <AntDesign.Column Title="Cron" DataIndex="Cron" TData="string" />
        <AntDesign.Column Title="任务类名" DataIndex="ActionClass" TData="string" />
        <AntDesign.Column Title="描述" DataIndex="Remark" TData="string" />
        <AntDesign.Column Title="请求方式" DataIndex="RequestType" TData="string" />
        <AntDesign.Column Title="请求地址" DataIndex="ApiUrl" TData="string" />
        <AntDesign.Column Title="密匙名" DataIndex="AuthKey" TData="string" />
        <AntDesign.Column Title="密匙值" DataIndex="AuthValue" TData="string" />
        <ActionColumn Title="Action" Fixed="right">
            <Space Size=@("small")>
                <SpaceItem>
                    <Button Type="@ButtonType.Link" Style="padding:0px" OnClick="()=>Edit(context)">Edit</Button>
                    <Popconfirm Title="确认删除吗?" 
                                OnConfirm="()=>Delete(context.Id)"
                                OnCancel="()=>{}"
                                OkText="确定"
                                CancelText="取消">
                        <Button Danger Type="@ButtonType.Link" Style="padding:0px">Delete</Button>
                    </Popconfirm>
                    <Button Type="@ButtonType.Link" Style="padding:0px" OnClick="()=>Log(context)">Log</Button>
                </SpaceItem>
            </Space>
        </ActionColumn>
    </ChildContent>
    <PaginationTemplate>
        <div style="float:right;margin-top:10px">
            <Pagination Total="Pagination.Total"
                        ShowTotal="ShowTotal"
                        ShowSizeChanger
                        PageSize="Pagination.PageRows"
                        Current="Pagination.PageIndex"
                        OnChange="PageIndexChanged"
                        OnShowSizeChange="PageSizeChanged" />
        </div>
    </PaginationTemplate>
</Table>

<style>
    .gray-2 {
        background-color: #fafafa;
    }
</style>

@code
{
    public List()
    {
        Area = "Quartz_Manage";
        NewTitle = "新建任务";
        EditTitle = "编辑任务";
    }

    private async void Log(Quartz_TaskDTO para)
    {
        var modalConfig = new ModalOptions();
        modalConfig.Title = "查看日志";
        //modalConfig.Style = "top:20px;";
        // In order for Dispose in ConfirmTemplateDemo to take effect every time it is closed
        //modalConfig.BodyStyle += "overflow-y: auto;";
        modalConfig.DestroyOnClose = true;
        modalConfig.Centered = true;
        modalConfig.Width = 1000d;
        var modalRef = await ModalService.CreateModalAsync<LogForm, string>(modalConfig, para.GroupName + "." + para.TaskName);

    }

    private void Pause(string? id = null)
    {
        List<string> ids;
        if (string.IsNullOrEmpty(id))
        {
            ids = SelectedItems.Select(p => p.Id).ToList();
        }
        else
        {
            ids = new List<string> { id };
        }
        Excute("暂停", "PauseData", ids);
    }

    private void Start(string? id = null)
    {
        List<string> ids;
        if (string.IsNullOrEmpty(id))
        {
            ids = SelectedItems.Select(p => p.Id).ToList();
        }
        else
        {
            ids = new List<string> { id };
        }
        Excute("开始", "StartData", ids);
    }

    private void ToDo(string? id = null)
    {
        List<string> ids;
        if (string.IsNullOrEmpty(id))
        {
            ids = SelectedItems.Select(p => p.Id).ToList();
        }
        else
        {
            ids = new List<string> { id };
        }
        Excute("立即执行", "ToDoData", ids);
    }

    private void Excute(string Text, string Action, List<string> ids)
    {

        Func<ModalClosingEventArgs, Task> onOkClick = async (e) =>
            {
                using (var waitfor = WaitFor.GetWaitFor(this))
                {
                    try
                    {
                        var result = await DataProvider.PostData<AjaxResult>($"/Quartz_Manage/Quartz_Task/{Action}", ids.ToJson());
                        if (!result.Success)
                        {
                            throw new MsgException(result.Msg);
                        }
                        await GetData();
                        StateHasChanged();
                    }
                    catch (Exception ex)
                    {
                        await Error.ProcessError(ex);
                    }
                }
        };

        RenderFragment icon = (builder) =>
        {
            var index = 0;
            IEnumerable<KeyValuePair<string, object>> paramenter = new List<KeyValuePair<string, object>>()
                    {
                new KeyValuePair<string, object>("Type","check-circle")
                    };

            builder.OpenComponent(index++, typeof(Icon));
            builder.AddMultipleAttributes(index++, paramenter);
            builder.CloseComponent();

        };
        ModalService.Confirm(new ConfirmOptions()
            {
                Title = $"任务{Text}",
                Icon = icon,
                Content = $"确认{Text}吗？",
                Centered = true,
                OnOk = onOkClick
            });
    }


}